package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    @Autowired
    private RestHighLevelClient client;

    //删除
    @Override
    public void deleteById(Long id) throws IOException {
        DeleteRequest request = new DeleteRequest("hotel");

        client.delete(request, RequestOptions.DEFAULT);
    }

    //新增和更新
    @Override
    public void insertById(Long id) throws IOException {

        //根据id酒店数据
        Hotel hotel = getById(id);
        //转换为文档类型
        HotelDoc hotelDoc = new HotelDoc(hotel);

        //准备request
        IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
        //准备Json
        request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
        //发送请求
        client.index(request, RequestOptions.DEFAULT);
    }

    /**
     * 自动补全功能
     *
     * @param key
     * @return
     */
    @Override
    public List<String> suggestion(String key) {
        //准备request
        SearchRequest request = new SearchRequest("hotel");
        //准备DSL
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "suggestions",//自定义查询名称
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(key)//前缀
                        .skipDuplicates(true)//忽略重复
                        .size(10)
        ));
        //发起请求
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            Suggest suggest = response.getSuggest();
            //根据补全查询名称，获取补全结果
            CompletionSuggestion suggestion = suggest.getSuggestion("suggestions");
            //获取options
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            //遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                list.add(option.getText().toString());
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 搜索页面的品牌、城市等信息不应该是在页面写死，而是通过聚合索引库中的酒店数据得来的：
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        //创建搜索对象
        SearchRequest request = new SearchRequest("hotel");
        //搜索条件设置，服用search方法
        buildBasicQuery(params, request);

        //设置聚合处理 要求 按照 品牌 星级 城市 进行terms分桶
        request.source().size(0);
        //聚合
        buildAggregation(request);
//        request.source().aggregation(
//                AggregationBuilders.terms("brand_agg")
//                        .field("brand")
//                        .size(20)
//        );
//
//        request.source().aggregation(
//                AggregationBuilders.terms("star_agg")
//                        .field("starName")
//                        .size(20)
//        );
//
//        request.source().aggregation(
//                AggregationBuilders.terms("city_agg")
//                        .field("city")
//                        .size(20)
//        );

        //执行搜索
        try {
            //发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //获取聚合结果
            Aggregations aggregations = response.getAggregations();

            //解析结果
            Map<String, List<String>> result = new HashMap<>();

            //根据品牌名称，获取品牌结果
            List<String> brandAggList = getAggByName(aggregations, "brand_agg");
            result.put("brand", brandAggList);

            List<String> starAggList = getAggByName(aggregations, "star_agg");
            result.put("starName", starAggList);

            List<String> cityAggList = getAggByName(aggregations, "city_agg");
            result.put("city", cityAggList);


            return result;

//            List<String> list = new ArrayList<>();
//            Terms brandAgg = aggregations.get("brand_agg");
//            List<? extends Terms.Bucket> brandAggBuckets = brandAgg.getBuckets();
//            for (Terms.Bucket brandAggBucket : brandAggBuckets) {
////                brandAggBucket.getKeyAsString();
//                list.add(brandAggBucket.getKeyAsString());
//            }

//            Terms starAgg = aggregations.get("star_agg");
//            Terms cityAgg = aggregations.get("city_agg");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //解析响应聚合结果

    }

    //根据品牌名称获取品牌结果 抽取出来
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        //根绝聚合名称获取聚合结果
        Terms brandAgg = aggregations.get(aggName);
        //获取buckets
        List<? extends Terms.Bucket> brandAggBuckets = brandAgg.getBuckets();
        //遍历
        List<String> list = new ArrayList<>();
        for (Terms.Bucket brandAggBucket : brandAggBuckets) {
            //获取key
//                brandAggBucket.getKeyAsString();
            //加入集合
            list.add(brandAggBucket.getKeyAsString());
        }
        return list;
    }

    //把聚合抽离出来
    public void buildAggregation(SearchRequest request) {
        request.source().aggregation(
                AggregationBuilders.terms("brand_agg")
                        .field("brand")
                        .size(20)
        );

        request.source().aggregation(
                AggregationBuilders.terms("star_agg")
                        .field("starName")
                        .size(20)
        );

        request.source().aggregation(
                AggregationBuilders.terms("city_agg")
                        .field("city")
                        .size(20)
        );
    }

    @Override
    public PageResult search(RequestParams params) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("hotel");
            // 2.准备DSL
            // 2.1.query
            buildBasicQuery(params, request);

            // 2.2.分页
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page - 1) * size).size(size);

            //2.3 地理位置排序
            String location = params.getLocation();
            if (location != null && !location.equals("")) {
                request.source().sort(SortBuilders
                        .geoDistanceSort("location", new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS)
                );
            }


            //3.排序
            //3.1 价格
            String sortBy = params.getSortBy();
            if ("price".equals(sortBy)) {
                request.source().sort("price", SortOrder.ASC);

            }
            //3.2 评分
            if ("score".equals(sortBy)) {
                request.source().sort("score", SortOrder.DESC);
            }

            //广告费排名
            if ("default".equals(sortBy)) {
                request.source().sort("ADcost", SortOrder.DESC);
            }


            //高亮
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

            // 3.发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析响应
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        //1.构建BooleanQuery
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //2.关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        }

        //3.城市条件
        if (params.getCity() != null && !params.getCity().equals("")) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", params.getCity()));
        }
        // 4.品牌条件
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        // 5.星级条件
        if (params.getStarName() != null && !params.getStarName().equals("")) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", params.getStarName()));
        }
        // 6.价格
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(params.getMinPrice())
                    .lte(params.getMaxPrice())
            );
        }


        //算分控制
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                //原始查询，相关性算分的查询
                boolQueryBuilder,
                //function score数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        //其中一个function score元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //过滤条件
                                QueryBuilders.termQuery("isAD", true),
                                //算分函数
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
        );

        request.source().query(functionScoreQuery)
        ;
    }

    private PageResult handleResponse(SearchResponse response) {
        //3.解析响应
        SearchHits hits = response.getHits();
        //总条数
        long total = hits.getTotalHits().value;

        //获取文档数组
        SearchHit[] searchHits = hits.getHits();

        //遍历
        List<HotelDoc> hotelDocs = new ArrayList<>(searchHits.length);

        //遍历文档数组 获取数据
        for (SearchHit hit : searchHits) {
            //获取source
            String jsonStr = hit.getSourceAsString();
            //反序列化
            HotelDoc hotelDoc = JSON.parseObject(jsonStr, HotelDoc.class);

            //获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                //根据字段名获取高亮结果
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    //获取高亮值
                    String name = highlightField.getFragments()[0].string();
                    //覆盖高亮结果
                    hotelDoc.setName(name);

                }

            }
            //获取排序值
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length > 0) {
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);

            }
            //加入集合
            hotelDocs.add(hotelDoc);
        }

        return new PageResult(total, hotelDocs);

    }
}